<?php
require_once 'vendor/autoload.php';

/**
 * 消息推送驱动器组件：SMS.XFunionSMS[消息子模型-SMS.企业信使]
 * 
 * @date	2017年7月19日 下午7:24:38
 * 
 */
class MessagePusherSms_XFunionSMS extends CI_Driver implements libraries\common\MessagePusherInterface
{
	const DEBUG_MODE = false;
	private $userId   = "";
	private $userName = "";
	private $userPass = "";
	private $comSign  = "";
	private $extno    = "";
	private $url      = 'http://125.208.3.91:8888/sms.aspx';
	private $lastResponse    = null;
	
	public function __set($var, $val)
	{
		$this->$var = $val;
	}
	
	public function __construct($config = array())
	{
		
	}
	
	/**
	 * 给定数据执行推送
	 *
	 * @param array $data
	 *
	 * @return void
	 */
	public function pushPerform($data)
	{
		if(self::DEBUG_MODE) {
			return ;
		}
		$mobile  = $data['mobile'];
		$message = $data['msg'];
		$this->lastResponse = $this->send($mobile, $message);
	}
	
	/**
	 * 获取上一次推送的状态
	 *
	 * @return boolean
	 */
	public function getStatus()
	{
		if(self::DEBUG_MODE) {
			return true;
		}
		$simpleXMLElement = $this->getParsedResponse();
		if($simpleXMLElement && $simpleXMLElement->returnstatus == 'Success') {
			return true;
		}
		
		return false;
	}
	
	public function getMessage()
	{
		$simpleXMLElement = $this->getParsedResponse();
		if($simpleXMLElement) {
			return $simpleXMLElement->message;
		}
		
		return false;
	}
	
	private function getParsedResponse()
	{
		if(!isset($this->lastResponse)) {
			//FIXME trigger_error???
			//trigger_error(sprintf("%s::%s: You Shouldn't call me here, because no response now!", __CLASS__, __METHOD__), E_USER_ERROR);
			return false;
		}
		
		$response = $this->lastResponse;
		$simpleXMLElement = @simplexml_load_string($response);
		
		//print_r($simpleXMLElement);
		return $simpleXMLElement;
	}
	
	private function send($mobile, $message)
	{
		$params = array(
				'action'  => 'send',
				'userid'  => $this->userId,
				'account' => $this->userName,
				'password' => $this->userPass,
				'mobile'   => $mobile,
				'content'  => $message . '【' . $this->comSign . '】',
				'extno'    => $this->extno,
		);
		
		$this->pushUrl = $this->url . '?' . http_build_query($params);
		try {
			$request = Requests::get($this->pushUrl);
		} catch (\Exception $e) {
			//var_dump($e);
			return null;
		}
		
		$response = $request->body;
		
		return $response;
	}
	
}